package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PowerSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DatePickerDlg;
import jp.co.sharp.android.parents.kidsguard.common.DateTimePickerDlg;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.dto.ScheduleDetailDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class ScheduleEditActivity extends AppCompatActivity {

    private final static int SCHEDULE_EDIT_CODE = 1000;

    private final static int SCHEDULE_EDIT_REPEAT_CODE = 100;

    private App mApp;

    private ImageView mBackIv;

    private ImageView mDeleteIv;

    private EditText mTitleEv;

    private ImageView mTitleResetIv;

    private Switch mAllDaySw;

    private TextView mStartYearTv;

    private TextView mStartHourTv;

    private TextView mEndYearTv;

    private TextView mEndHourTv;

    private TextView mRepeatTv;

    private Switch mAlarmSw;

    private EditText mMemoEv;

    private ImageView mMemoResetIv;

    private Button mSubmitBtn;

    public ParentBleTransfer mParentBleTransfer;

    private String mode;

    private ScheduleDetailDto mScheduleDetailDto;

    private ScheduleDetailDto mScheduleDetailOldDto;

    private DelDeviceConfirmDlg mDelDeviceConfirmDlg;

    private boolean mScreenOperate = false;

    private Boolean mOnSyncResultFlag = false;

    private DealWithWaitingDlg mDealWithWaitingDlg;

    private KidInfoEntity mKidInfoEntity;

    private boolean mUnReceiver = true;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    private static final String TAG = "TAG";
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule_edit);
        mApp = (App)getApplication();
        //页面初始化方法
        try {
            mounted();
        } catch (CloneNotSupportedException e) {
            Log.e(TAG,e.getMessage());
        }
        //初始化绑定事件
        initListener();
        //
        initReceiver();
    }

    @Override
    public void onBackPressed() {
        if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
            backToScheduleListActivity();
        }else {
            String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
            mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(ScheduleEditActivity.this, R.style.commonDlg, message);
            mDelDeviceConfirmDlg.show();
            mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                @Override
                public void onOperateSet() {
                    backToScheduleListActivity();
                    mDelDeviceConfirmDlg.dismiss();
                }
            });
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ScheduleEditActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        initReceiver();
        if (requestCode == SCHEDULE_EDIT_REPEAT_CODE) {
            if (intent.hasExtra("repeat") && null != intent.getStringExtra("repeat")) {
                mScheduleDetailDto.setRepeat(Integer.parseInt(intent.getStringExtra("repeat")));
                switch (mScheduleDetailDto.getRepeat()) {
                    case -1:
                        mRepeatTv.setText("繰り返しない");
                        break;
                    case 0:
                        mRepeatTv.setText("毎日");
                        break;
                    case 1:
                        mRepeatTv.setText("毎週");
                        break;
                    case 2:
                        mRepeatTv.setText("毎月");
                        break;
                    case 3:
                        mRepeatTv.setText("毎年");
                        break;
                }
                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "ScheduleEditActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if ((mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT)&&(!mEditReopening)) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleEditActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mEditReopening = true;
                    sendIsUsingToKid();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                }
                mSystemHomeFlag = false;
            }
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ScheduleEditActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ScheduleEditActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    private void mounted() throws CloneNotSupportedException {

        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        TextView mKidNameTv = findViewById(R.id.textViewKidName);
        String kidNameDescribe = mKidInfoEntity.getKidName()+"のキッズケータイ";
        mKidNameTv.setText(kidNameDescribe);
        mBackIv = (ImageView) this.findViewById(R.id.imageViewBack);
        mDeleteIv = (ImageView) this.findViewById(R.id.imageViewDelete);
        mTitleEv = (EditText) this.findViewById(R.id.editViewTitle);
        mTitleResetIv = (ImageView) this.findViewById(R.id.imageViewTitleReset);
        mStartYearTv = (TextView) this.findViewById(R.id.textViewStartYear);
        mStartHourTv = (TextView) this.findViewById(R.id.textViewStartHour);
        mEndYearTv = (TextView) this.findViewById(R.id.textViewEndYear);
        mEndHourTv = (TextView) this.findViewById(R.id.textViewEndHour);
        mRepeatTv = (TextView) this.findViewById(R.id.textViewRepeat);
        mAlarmSw = (Switch) this.findViewById(R.id.switchAlarm);
        mAllDaySw = (Switch) this.findViewById(R.id.switchAllDay);
        mMemoEv = (EditText) this.findViewById(R.id.editTextMemo);
        mMemoResetIv = (ImageView) this.findViewById(R.id.imageViewMemoReset);
        mSubmitBtn = (Button) this.findViewById(R.id.buttonSubmit);
        mSubmitBtn.setEnabled(false);
        mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));


        mode = getIntent().getStringExtra("MODE");

        if ("EDIT".equals(mode)) {
            mDeleteIv.setVisibility(View.VISIBLE);
            mScheduleDetailDto = (ScheduleDetailDto) getIntent().getSerializableExtra("INFO");
            mScheduleDetailOldDto = (ScheduleDetailDto) mScheduleDetailDto.clone();
            //title
            mTitleEv.setText(mScheduleDetailDto.getTitle());
            //start
            mStartYearTv.setText(mScheduleDetailDto.getStart().split(" ")[0].replace("-", "/"));
            mStartHourTv.setText(mScheduleDetailDto.getStart().split(" ")[1]);
            //end
            mEndYearTv.setText(mScheduleDetailDto.getEnd().split(" ")[0].replace("-", "/"));
            mEndHourTv.setText(mScheduleDetailDto.getEnd().split(" ")[1]);
            //memo
            mMemoEv.setText(mScheduleDetailDto.getMemo());
            //allDay
            mAllDaySw.setChecked(mScheduleDetailDto.getAllDay() == 0 ? true : false);
            //alarm
            mAlarmSw.setChecked(mScheduleDetailDto.getAlarm() == 0 ? false : true);
            //repeat
            switch (mScheduleDetailDto.getRepeat()) {
                case -1:
                    mRepeatTv.setText("繰り返しない");
                    break;
                case 0:
                    mRepeatTv.setText("毎日");
                    break;
                case 1:
                    mRepeatTv.setText("毎週");
                    break;
                case 2:
                    mRepeatTv.setText("毎月");
                    break;
                case 3:
                    mRepeatTv.setText("毎年");
                    break;
            }
        } else {
            mDeleteIv.setVisibility(View.GONE);
            mScheduleDetailDto = new ScheduleDetailDto();
            mScheduleDetailOldDto = new ScheduleDetailDto();
            mScheduleDetailDto.setId(-1);
            mScheduleDetailOldDto.setId(-1);
            //title
            mScheduleDetailDto.setTitle("");
            mScheduleDetailOldDto.setTitle("");
            mTitleEv.setText("");
            //start
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            mScheduleDetailDto.setStart(sdf2.format(new Date()));
            mScheduleDetailOldDto.setStart(sdf2.format(new Date()));
            mStartYearTv.setText(sdf3.format(new Date()));
            mStartHourTv.setText(sdf.format(new Date()));
            //end
            mScheduleDetailDto.setEnd(sdf2.format(new Date()));
            mScheduleDetailOldDto.setEnd(sdf2.format(new Date()));
            mEndYearTv.setText(sdf3.format(new Date()));
            mEndHourTv.setText(sdf.format(new Date()));
            //memo
            mScheduleDetailDto.setMemo("");
            mScheduleDetailOldDto.setMemo("");
            mMemoEv.setText("");
            //allDay
            mScheduleDetailDto.setAllDay(0);
            mScheduleDetailOldDto.setAllDay(0);
            mAllDaySw.setChecked(false);
            //alarm
            mScheduleDetailDto.setAlarm(1);
            mScheduleDetailOldDto.setAlarm(1);
            mAlarmSw.setChecked(false);
            //repeat
            mScheduleDetailDto.setRepeat(-1);
            mScheduleDetailOldDto.setRepeat(-1);
            mRepeatTv.setText("繰り返しない");
            //date
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            mScheduleDetailDto.setDate(sdf1.format(new Date()));
            mScheduleDetailOldDto.setDate(sdf1.format(new Date()));
        }
    }

    private void initListener() {
        //title
        // EditText焦点的监听
        mTitleEv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });
        mTitleEv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                mScheduleDetailDto.setTitle(s.toString());
                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });
        //memo
        mMemoEv.setMovementMethod(ScrollingMovementMethod.getInstance());
        mMemoEv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });
        mMemoEv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                mScheduleDetailDto.setMemo(s.toString());
                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });
        //imageViewBack
        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    backToScheduleListActivity();
                }else {
                    String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
                    mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(ScheduleEditActivity.this, R.style.commonDlg, message);
                    mDelDeviceConfirmDlg.show();
                    mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            backToScheduleListActivity();
                            mDelDeviceConfirmDlg.dismiss();
                        }
                    });
                }
            }
        });
        //imageViewTitleReset
        mTitleResetIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mScheduleDetailDto.setTitle("");
                mTitleEv.setText("");
                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });
        //imageViewDelete
        mDeleteIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = "このアラームを削除しますか？";
                DelDeviceConfirmDlg mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(ScheduleEditActivity.this, R.style.commonDlg, message);
                mDelDeviceConfirmDlg.show();
                mDelDeviceConfirmDlg.setOnOperateSetListener(() -> {
                    sendDeleteToKid();
                    mDelDeviceConfirmDlg.dismiss();
                });
            }
        });
        //switchAllDay
        mAllDaySw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAllDaySw.setChecked(mAllDaySw.isChecked());
                mScheduleDetailDto.setAllDay(mAllDaySw.isChecked() ? 1 : 0);
                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });

        //textViewRepeat
        mRepeatTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPageJumpFlag = true;
                Intent intent1 = new Intent();
                intent1.setClass(ScheduleEditActivity.this, ScheduleEditRepeatActivity.class);
                intent1.putExtra("repeat", mScheduleDetailDto.getRepeat());
                startActivityForResult(intent1, SCHEDULE_EDIT_REPEAT_CODE);
            }
        });
        //switchAlarm
        mAlarmSw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlarmSw.setChecked(mAlarmSw.isChecked());
                mScheduleDetailDto.setAlarm(mAlarmSw.isChecked() ? 0 : 1);
                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });
        //imageViewMemoReset
        mMemoResetIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMemoEv.setText("");
                mScheduleDetailDto.setMemo("");
                if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                    mSubmitBtn.setEnabled(false);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                }else {
                    mSubmitBtn.setEnabled(true);
                    mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                }
            }
        });
        //buttonSubmit
        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Dlg
                String message = "キッズケータイへ反映中..";
                mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleEditActivity.this, R.style.commonDlg, message, true);
                mDealWithWaitingDlg.show();
                sendToKid();
            }
        });

        //textViewStartYear
        mStartYearTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int pYear = Integer.parseInt(mScheduleDetailDto.getStart().split(" ")[0].split("-")[0]);
                int pMonth = Integer.parseInt(mScheduleDetailDto.getStart().split(" ")[0].split("-")[1]);
                int pDay = Integer.parseInt(mScheduleDetailDto.getStart().split(" ")[0].split("-")[2]);
                DatePickerDlg datePickerDlg = new DatePickerDlg(ScheduleEditActivity.this, R.style.commonDlg, pYear, pMonth, pDay);
                datePickerDlg.show();
                datePickerDlg.setOnDateSetListener(new DatePickerDlg.OnDateSetListener() {
                    @Override
                    public void onDateSet(int pYear, int month, int day) {
                        String pMonth;
                        if (month < 10) {
                            pMonth = "0" + month;
                        } else {
                            pMonth = month + "";
                        }
                        String pDay;
                        if (day < 10) {
                            pDay = "0" + day;
                        } else {
                            pDay = day + "";
                        }
                        mScheduleDetailDto.setStart(pYear + "-" + pMonth + "-" + pDay + " " + mScheduleDetailDto.getStart().split(" ")[1]);
                        mStartYearTv.setText(pYear + "/" + pMonth + "/" + pDay);
                        if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                            mSubmitBtn.setEnabled(false);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                        }else {
                            mSubmitBtn.setEnabled(true);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                        }
                    }
                });
            }
        });

        //textViewStartHour
        mStartHourTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String time = mScheduleDetailDto.getStart().split(" ")[1];
                String[] timeArr = time.split(":");
                Integer hour = Integer.valueOf(timeArr[0]);
                int prefix = 0;
                if (hour >= 12) {
                    prefix = 1;
                    hour = Math.abs(hour - 12);
                }
                int min = Integer.parseInt(mScheduleDetailDto.getStart().split(" ")[1].split(":")[1]);
                DateTimePickerDlg dateTimePickerDlg = new DateTimePickerDlg(ScheduleEditActivity.this, R.style.commonDlg, prefix, hour, min);
                dateTimePickerDlg.show();
                dateTimePickerDlg.setOnDateTimeSetListener(new DateTimePickerDlg.OnDateTimeSetListener() {
                    @Override
                    public void onDateTimeSet(int pAmPm, int hour, int minute) {
                        int pHourInt;
                        String pHour;
                        String pMinute;
                        if (pAmPm == 0) {
                            pHourInt = hour;
                        } else {
                            pHourInt = 12 + hour;
                        }
                        if (minute < 10) {
                            pMinute = "0" + minute;
                        } else {
                            pMinute = "" + minute;
                        }
                        if (pHourInt < 10) {
                            pHour = "0" + pHourInt;
                        } else {
                            pHour = "" + pHourInt;
                        }
                        mScheduleDetailDto.setStart(mScheduleDetailDto.getStart().split(" ")[0] + " " + pHour + ":" + pMinute);
                        mStartHourTv.setText(pHour + ":" + pMinute);
                        if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                            mSubmitBtn.setEnabled(false);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                        }else {
                            mSubmitBtn.setEnabled(true);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                        }
                    }
                });
            }
        });

        //textViewEndYear
        mEndYearTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int pYear = Integer.parseInt(mScheduleDetailDto.getEnd().split(" ")[0].split("-")[0]);
                int pMonth = Integer.parseInt(mScheduleDetailDto.getEnd().split(" ")[0].split("-")[1]);
                int pDay = Integer.parseInt(mScheduleDetailDto.getEnd().split(" ")[0].split("-")[2]);
                DatePickerDlg datePickerDlg = new DatePickerDlg(ScheduleEditActivity.this, R.style.commonDlg, pYear, pMonth, pDay);
                datePickerDlg.show();
                datePickerDlg.setOnDateSetListener(new DatePickerDlg.OnDateSetListener() {
                    @Override
                    public void onDateSet(int pYear, int month, int day) {
                        String pMonth;
                        if (month < 10) {
                            pMonth = "0" + month;
                        } else {
                            pMonth = month + "";
                        }
                        String pDay;
                        if (day < 10) {
                            pDay = "0" + day;
                        } else {
                            pDay = day + "";
                        }
                        mScheduleDetailDto.setEnd(pYear + "-" + pMonth + "-" + pDay + " " + mScheduleDetailDto.getEnd().split(" ")[1]);
                        mEndYearTv.setText(pYear + "/" + pMonth + "/" + pDay);
                        if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                            mSubmitBtn.setEnabled(false);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                        }else {
                            mSubmitBtn.setEnabled(true);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                        }
                    }
                });
            }
        });

        //textViewEndHour
        mEndHourTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String time = mScheduleDetailDto.getEnd().split(" ")[1];
                String[] timeArr = time.split(":");
                Integer hour = Integer.valueOf(timeArr[0]);
                int prefix = 0;
                if (hour >= 12) {
                    prefix = 1;
                    hour = Math.abs(hour - 12);
                }
                int min = Integer.parseInt(mScheduleDetailDto.getEnd().split(" ")[1].split(":")[1]);
                DateTimePickerDlg dateTimePickerDlg = new DateTimePickerDlg(ScheduleEditActivity.this, R.style.commonDlg, prefix, hour, min);
                dateTimePickerDlg.show();
                dateTimePickerDlg.setOnDateTimeSetListener(new DateTimePickerDlg.OnDateTimeSetListener() {
                    @Override
                    public void onDateTimeSet(int pAmPm, int hour, int minute) {
                        int pHourInt;
                        String pHour;
                        String pMinute;
                        if (pAmPm == 0) {
                            pHourInt = hour;
                        } else {
                            pHourInt = 12 + hour;
                        }
                        if (minute < 10) {
                            pMinute = "0" + minute;
                        } else {
                            pMinute = "" + minute;
                        }
                        if (pHourInt < 10) {
                            pHour = "0" + pHourInt;
                        } else {
                            pHour = "" + pHourInt;
                        }
                        mScheduleDetailDto.setEnd(mScheduleDetailDto.getEnd().split(" ")[0] + " " + pHour + ":" + pMinute);
                        mEndHourTv.setText(pHour + ":" + pMinute);
                        if (mScheduleDetailDto.equals(mScheduleDetailOldDto)){
                            mSubmitBtn.setEnabled(false);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
                        }else {
                            mSubmitBtn.setEnabled(true);
                            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
                        }
                    }
                });
            }
        });
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // Bluetooth
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        //isFinish
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            String message = "編集を再開しています...";
                            mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleEditActivity.this, R.style.commonDlg, message, false);
                            mDealWithWaitingDlg.show();
                            mScreenOperate = true;
                            mEditReopening = true;
                            sendIsUsingToKid();
                            // ブロードキャストの再登録
                            unregisterReceiver(systemReceiver);
                            initReceiver();
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (((App)getApplication()).isMimamoriCheck(macAddress)) {
                        ((App)getApplication()).addmLsIsMimamori(macAddress);
                        sendExitToKid();
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(ScheduleEditActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        ((App)getApplication()).updateKidInfo(mKidInfoEntity);
                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleEditActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(ScheduleEditActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                try {
                    JSONObject resp = new JSONObject(bluetoothReceiverDto.getRetStr());
                    String method = resp.getString("method");

                    if (null != method) {
                        if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(method)) {
                            JSONObject data = resp.getJSONObject("data");
                            if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                                sendEnterToKid();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleEditActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                        // ページジャンプ
                                        mPageJumpFlag = true;
                                        ScheduleEditActivity.this.finish();
                                    }
                                });
                            }
                        } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(method)) {
                            if (Constants.ON_SYNC_RESULT.equals(resp.getString("result"))) {
                                handler.sendEmptyMessage(0);
                                backToScheduleListActivity();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "キッズケータイへ反映できませんでした";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleEditActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                    }
                                });
                            }
                        } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(method)){
                            String message = "キッズケータイが操作されました。編集を中断します。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleEditActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    backToEditActivity();
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                     Log.e(TAG,e.getMessage());
                }

            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                //isFinish
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    if (mOnSyncResultFlag) {
                        mOnSyncResultFlag = false;
                        if (!mScreenOperate) {
                            backToScheduleListActivity();
                        }
                    }
                    if (!mScreenOperate) {

                    } else {
                        mScreenOperate = false;
                        mEditReopening = false;
                        handler.sendEmptyMessage(0);
                    }


                }

            }
        }
    };
    /**
     *  is using
     */
    public void sendIsUsingToKid() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "getOperatingState");
            jsonObject.put("data", JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        } catch (JSONException e) {
             Log.e(TAG,e.getMessage());
        } catch (Exception e) {
             Log.e(TAG,e.getMessage());
        }
    }

    /**
     * enter
     */
    public void sendEnterToKid() {
        try {
            new BusinessThread(Constants.SEND_KID_ENTER,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    null,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        } catch (Exception e) {
             Log.e(TAG,e.getMessage());
        }
    }


    /**
     * exit
     */
    public void sendExitToKid() {
        try {
            mOnSyncResultFlag = true;
            new BusinessThread(Constants.SEND_KID_EXIT,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    null,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        } catch (Exception e) {
             Log.e(TAG,e.getMessage());
        }

    }

    public void sendDeleteToKid() {
        try {
            JSONObject jsonData = new JSONObject();
            jsonData.put("method", "deleteSchedule");
            jsonData.put("data", mScheduleDetailDto.getId());
            new BusinessThread(Constants.SEND_KID_SET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonData,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        } catch (JSONException e) {
             Log.e(TAG,e.getMessage());
        }

    }

    public void sendToKid() {
        try {
            JSONObject jsonData = new JSONObject();
            jsonData.put("method", "addSchedule");
            JSONObject insertData = new JSONObject();
            insertData.put("id", mScheduleDetailDto.getId());
            insertData.put("title", mScheduleDetailDto.getTitle());
            insertData.put("memo", mScheduleDetailDto.getMemo());
            insertData.put("start", mScheduleDetailDto.getStart());
            insertData.put("end", mScheduleDetailDto.getEnd());
            insertData.put("allDay", mScheduleDetailDto.getAllDay());
            insertData.put("repeat", mScheduleDetailDto.getRepeat());
            insertData.put("alarm", mScheduleDetailDto.getAlarm());
            insertData.put("date", mScheduleDetailDto.getDate());
            jsonData.put("data", insertData);
            new BusinessThread(Constants.SEND_KID_SET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonData,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        } catch (JSONException e) {
             Log.e(TAG,e.getMessage());
        }
    }

    private void backToScheduleListActivity() {
        mPageJumpFlag = true;
        Intent intent = getIntent();
        setResult(SCHEDULE_EDIT_CODE, intent);
        finish();
    }

    private void backToEditActivity() {
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(this, EditActivity.class);
        startActivity(intent);
    }


    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
        }
    };


}
